<?php
namespace Erp\C\Orders\Tn\Shipping;
use Fn;
	/*
	*各个运输方式API业务逻辑模块基类
    *@date: 2014-12-9
    */

/*
	各个运输方式api必须实现以下2个方法
	getTn($orders)  	// array $orders 一维数组，订单集合
	getLable($orders) 	// array $orders 一维数组，订单集合
*/
abstract class Shipping{
	/**
	 *运输方式入口文件
	 *@param array $data array(orders_id1,orders_id2) ||  string  $data orders_id
	 */
	abstract public function getTn($data);

	//生成创建线上订单包裹需要的数据
	 abstract public function createPackageParams($array);

	//api请求创建线上包裹
	//abstract public function createPackage($data);

	//_sendOrdersPackage 返回处理
	abstract public function disposePackageReturn($data);

	//api请求获取包裹标签pdf
	//abstract public function createPackageLable($code,$array);

	//_createPackageLable 返回处理
	//abstract public function disposeLableReturn();

	/**
	 *XML编码
	 *@param
	 */
	protected function xmlEncode($p, $act){
		return '<?xml version="1.0" encoding="utf-8"?>'.
				'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
			<soap:Body>
				<'.$act.' xmlns="http://shippingapi.ebay.cn/">
					<'.$act.'Request>
						'.$this -> _xmlEncode($p).'
					</'.$act.'Request>
				</'.$act.'>
			</soap:Body>
		</soap:Envelope>';
	}
	protected function _xmlEncode($p){
		$r = '';
		foreach ($p as $k=>$v){
			$attr = '';
			if(is_array($v) || is_object($v)){
				//---------------------------
				if(is_array($v) || is_object($v)){
					if(!is_numeric(key($v))){
						$v = $this->_xmlEncode($v);
					}else{
						foreach ($v as $content){
							if(is_array($content) || is_object($content)){
								$r .= "<$k>".($this->_xmlEncode($content))."</$k>\n";
							}else{
								$r .= "<$k>$content</$k>\n";
							}
						}
						return $r;
					}
				}
			}
			$r .= '<'.$k.$attr.'>'.$v."</$k>\n";
		}
		return $r;
	}

	/**
	 *XML解码
	 *@param
	 */
	public function xmlDecode($xml,$toArra=false)
	{
		//XML属性分析
		$xml = preg_replace('/(<.*?>)\s*(<.*?>)/', '$1'."\n".'$2' , $xml);
		$xml = preg_replace('/(<\w.*?>)\s(<\/.*?>)/', '$1EOS_NULL_EOL$2' , $xml);//++++++++++
		/* $xml = preg_replace('/(<.*?>)\s{2,}(<.*?>)/', '$1'."\n".'$2' , $xml);*/
		$xml = preg_replace('/(<\w*\s+\w*=.*?>)(.*?)(<.*?>)/','$1<val>$2</val>$3', $xml);
		$r = str_replace('EOS_NULL_EOL','',json_encode(simplexml_load_string($xml)));
		return json_decode($r,$toArra);
	}

	/**
	 *多线程http请求
	 *@param array $request array('id'=>array('url'=>'www.xx.com','post'=>'data','header'=>'xxx'))
	 */
	protected function multiCurl($request,$callback=false){
		$mh = curl_multi_init();
		foreach ($request as $i => $v) {
			$timeOut = (isset($v['timeout']) && $v['timeout']>0 )? $v['timeout'] :60;
			$conn[$i] = curl_init();
			curl_setopt($conn[$i], CURLOPT_URL,$v['url']);
			curl_setopt($conn[$i], CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($conn[$i], CURLOPT_SSL_VERIFYHOST, 0);
			if(isset($v['header']) && !empty($v['header'])){
				curl_setopt($conn[$i], CURLOPT_HTTPHEADER, $v['header']);
			}if(isset($v['post']) && !empty($v['post'])){
				$post = is_array($v['post']) ? http_build_query($v['post']) :$v['post'];
				curl_setopt($conn[$i], CURLOPT_POST, 1);
				curl_setopt($conn[$i], CURLOPT_POSTFIELDS, $post);
			}else{
				curl_setopt($conn[$i], CURLOPT_POST, 0);
			}
			curl_setopt($conn[$i], CURLOPT_CONNECTTIMEOUT,$timeOut);
			curl_setopt($conn[$i], CURLOPT_RETURNTRANSFER,1);
			curl_multi_add_handle ($mh,$conn[$i]);
		}
		do {
			$mrc = curl_multi_exec($mh, $active);
		} while ($mrc == CURLM_CALL_MULTI_PERFORM);

		while ($active and $mrc == CURLM_OK){
			if (curl_multi_select($mh) != -1){
				do {
					$mrc = curl_multi_exec($mh, $active);
				} while ($mrc == CURLM_CALL_MULTI_PERFORM);
			}
		}
		$r = array();
		foreach ($request as $i => $v) {
			$data = curl_multi_getcontent($conn[$i]);
			curl_multi_remove_handle($mh,$conn[$i]);
			curl_close($conn[$i]);
			if($callback){
				if(is_array($callback)){
					$fun = $callback[1];
					$r[$i] = $callback[0]->$fun($data,$request[$i]);	//回调函数处理返回内容
				}else{
					$r[$i] = $callback($data,$request[$i]);
				}
			}else{
				$r[$i] = $data;
			}
		}
		curl_multi_close($mh);
		return $r;
	}

	/**
	 *单线程http请求
	 *@param
	 */
	protected function oneHttpRequest($url,$data='',$method='POST',$headers='',$timeOut=60){
		$connection = curl_init();
		curl_setopt($connection, CURLOPT_URL, $url);
		curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, 1);
		curl_setopt($connection, CURLOPT_SSL_VERIFYHOST, 1);
		if($headers){
			curl_setopt($connection, CURLOPT_HTTPHEADER, $headers);
		}
		if($method=='POST'){
			curl_setopt($connection, CURLOPT_POST, 1);
			curl_setopt($connection, CURLOPT_POSTFIELDS, $data);
		}else{
			curl_setopt($connection, CURLOPT_HTTPGET, true);
		}
		curl_setopt($conn[$i], CURLOPT_CONNECTTIMEOUT,$timeOut);
		curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1);
		$response = curl_exec($connection);
		curl_close($connection);
		return $response;
	}

	/**
	 *合并一条订单信息
	 *@param init $orders_id
	 */
	protected function _combineOrdersInfo($orders_id){

	}

	//特殊字符进行转义
	protected function htmlspecialData($data){
		foreach ($data as $k=>$v){
			if(!is_array($v)){
				$data[$k]=trim(htmlspecialchars($v,ENT_QUOTES));
			}else{
				$data[$k]=$this->htmlspecialData($v);
			}
		}
		return $data;
	}

	//获取产品的报关名
	public function getCustomsClassname($v,$pid,$shipMethod){
		if(in_array($shipMethod, array('DG_TN','DGPT','CNPT','DGWISH_TN','DGWISH','OWAU','OSAU','YWWISH','YWWISH_TN'))){
			return $this->getRealCustomsName($pid);
		}
		$tmp = substr($v, -1);
		$sql = 'SELECT d.classname_for_customs, d.classname_for_customs_cn FROM dirname_for_customs d LEFT JOIN product_dir pd ON pd.classname_id_for_customs = d.classname_id_for_customs WHERE pd.dir_id=('.$v.') LIMIT 1';
		$obj=M()->query($sql);
		if (empty($obj)){
			if($tmp === '0' || $tmp === '1'){
				return array('ClassnameForCustoms' => 'Plug metal', 'ClassnameForCustomsCn' => '转接头');
			}elseif($tmp === '2' || $tmp === '3') {
				return array('ClassnameForCustoms' => 'nail separator', 'ClassnameForCustomsCn' => '美甲分指排');
			}elseif($tmp === '4' || $tmp === '5') {
				return array('ClassnameForCustoms' => 'Memory Card', 'ClassnameForCustomsCn' => '记忆盘');
			}elseif($tmp === '6' || $tmp === '7') {
				return array('ClassnameForCustoms' => 'Card Case', 'ClassnameForCustomsCn' => '卡包');
			}else{
				return array('ClassnameForCustoms' => 'False Eyelashes', 'ClassnameForCustomsCn' => '假睫毛');
			}

		} else {
			foreach($obj as $v){
				$ClassnameForCustoms = $v['classname_for_customs'];
				$ClassnameForCustomsCn = $v['classname_for_customs_cn'];
				if(strlen($ClassnameForCustomsCn)<6){
					if($tmp === '0' || $tmp === '1'){
						$ClassnameForCustomsCn="转接头";
						$ClassnameForCustoms="Plug metal";
					}elseif($tmp === '2' || $tmp === '3') {
						$ClassnameForCustomsCn="美甲分指排";
						$ClassnameForCustoms="nail separator";
					}elseif($tmp === '4' || $tmp === '5') {
						$ClassnameForCustomsCn="记忆盘";
						$ClassnameForCustoms="Memory Card";
					}elseif($tmp === '6' || $tmp === '7') {
						$ClassnameForCustomsCn="卡包";
						$ClassnameForCustoms="Card Case";
					}else{
						$ClassnameForCustomsCn="假睫毛";
						$ClassnameForCustoms="False Eyelashes";
					}
				}
			}
			return array('ClassnameForCustoms' => $ClassnameForCustoms, 'ClassnameForCustomsCn' => $ClassnameForCustomsCn);
		}
	}

	public function getRealCustomsName($pid){
		// $product_info = M('Product')->where( array("product_id"=>$pid) )->find();
		$product_info = A('Product')->getProduct($pid);
		$NameEn = $product_info['product_declaration_en'];
		$NameCn = $product_info['product_declaration_cn'];
		return array('ClassnameForCustoms' => $NameEn, 'ClassnameForCustomsCn' => $NameCn);
	}

	protected function saveShippingLable($dir,$fileName,$content){
		if (!file_exists($dir)){
			mkdir($dir,0777,true);
			chmod($dir,0777);
		}
		$fileName = $dir.$fileName;
		$fd = fopen($fileName,'wb');
		$pdf=fwrite($fd, $content);
		fclose($fd);
		$size=filesize($fileName)/1024;
		if($size>16){
			return true;
		}else{
			return false;
		}
	}

	public function turnToPdf($data,$outPath){
		Vendor('tcpdf.examples.OrderSum');
		$pdf = new \PPPPPPP();
		foreach ($data as $key => $value) {
			$filePath = $value['filePath'];
			$size = $value['size'];
			$fromat = $value['fromat'];
			$pdf->_tcpPdf->AddPage($fromat,$size);
			$pdf->_tcpPdf->Image($filePath, 0, 0, 0, 0, '', '', '', true, 300, 'C', false, false, 0);
		}
		$pdf->_savePdf($outPath);
	}

}





